﻿using UtilPublic.ServerLoger;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using UtilLib;

namespace UtilPublic.Http
{
    /// <summary>
    /// 公共类
    /// </summary>
    public static partial class HttpPublic
    {
        /// <summary>
        /// 解析 Content-type:multipart/form-data 格式
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static Dictionary<string, string> ParserContenttypemultipartformdata(string content)
        {
            var result = new Dictionary<string, string>();

            var listline = content.ToListString("\r\n");
            string key = "";
            string value = "";
            foreach (var line in listline)
            {
                if (line.IsNullOrEmpty())
                {
                    continue;
                }
                if (line.StartsWith("--"))
                {
                    continue;
                }
                if (line.StartsWith("Content"))
                {
                    key = line.GetMidStr("name=\"", "\"");
                    continue;
                }
                value = line;
                result[key] = value;
            }

            return result;
        }
        /// <summary>
        /// 发送http post请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="parameters">查询参数集合</param>
        /// <returns></returns>
        public static string CreatePostHttpResponse(string url, IDictionary<string, string> parameters)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求对象
            request.Method = "POST";//请求方式
            request.ContentType = "application/x-www-form-urlencoded";//链接类型
                                                                      //构造查询字符串
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                bool first = true;
                foreach (string key in parameters.Keys)
                {

                    if (!first)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        first = false;
                    }
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                //写入请求流
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return GetResponseString((HttpWebResponse)request.GetResponse());

        }
        /// <summary> /// 发送http Get请求 /// </summary> 
        /// <param name="url"></param> 
        /// <returns></returns> 
        public static string CreateGetHttpResponse(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";//链接类型 
            return GetResponseString((HttpWebResponse)request.GetResponse());
        }

        /// <summary> /// 从HttpWebResponse对象中提取响应的数据转换为字符串 /// </summary> 
        /// <param name="webresponse"></param> 
        /// <returns></returns> 
        public static string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8); return reader.ReadToEnd();
            }
        }
    }
    /// <summary>
    /// 公共类
    /// </summary>
    public static partial class HttpPublic
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceStr"></param>
        /// <returns></returns>
        public static string ToMD5(string sourceStr)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceStr));
                string md5Str = "";
                for (int i = 0; i < hash.Length; i++)
                    md5Str = md5Str + hash[i].ToString("x2");
                return md5Str;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static Dictionary<string, object> Deserialize(string jsonString)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Deserialize<Dictionary<string, object>>(jsonString);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="nvc"></param>
        static void Dic2Nvc(Dictionary<string, object> dic, NameValueCollection nvc)
        {
            foreach (KeyValuePair<string, object> kv in dic)
            {
                if (kv.Value is Dictionary<string, object>)
                    Dic2Nvc(kv.Value as Dictionary<string, object>, nvc);
                else
                    nvc[kv.Key] = kv.Value.ToString();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static NameValueCollection IsJasonString(string content)
        {
            NameValueCollection result = null;
            try
            {
                content = content.TrimEnd(new char[' ']);
                Dictionary<string, object> dic = Deserialize(content);
                result = new NameValueCollection();
                Dic2Nvc(dic, result);
            } catch { }
            return result;
        }
    }
}
